const { sequelize } = require('../config/database');
require('dotenv').config();

async function addUserProfileFields() {
    try {
        console.log('开始为visitors表添加用户信息字段...');
        
        const queryInterface = sequelize.getQueryInterface();
        
        const tables = await queryInterface.showAllTables();
        if (!tables.includes('visitors')) {
            console.log('visitors表不存在，无法添加字段');
            return;
        }
        
        const tableDescription = await queryInterface.describeTable('visitors');
        console.log('当前表结构:', Object.keys(tableDescription));
        
        // 添加性别字段
        if (!tableDescription.gender) {
            console.log('添加gender字段...');
            await queryInterface.addColumn('visitors', 'gender', {
                type: sequelize.Sequelize.ENUM('male', 'female', 'other'),
                allowNull: true,
                comment: '用户性别'
            });
            console.log('gender字段添加成功！');
        } else {
            console.log('gender字段已存在，跳过');
        }
        
        // 添加电话号码字段
        if (!tableDescription.phone) {
            console.log('添加phone字段...');
            await queryInterface.addColumn('visitors', 'phone', {
                type: sequelize.Sequelize.STRING,
                allowNull: true,
                comment: '用户电话号码'
            });
            console.log('phone字段添加成功！');
        } else {
            console.log('phone字段已存在，跳过');
        }
        
        // 添加会员等级字段
        if (!tableDescription.membership_tier) {
            console.log('添加membership_tier字段...');
            await queryInterface.addColumn('visitors', 'membership_tier', {
                type: sequelize.Sequelize.INTEGER,
                allowNull: true,
                defaultValue: null,
                comment: '会员等级：1=一级会员，2=二级会员，3=三级会员，null=普通用户'
            });
            console.log('membership_tier字段添加成功！');
        } else {
            console.log('membership_tier字段已存在，跳过');
        }
        
        const newTableDescription = await queryInterface.describeTable('visitors');
        console.log('新表结构:', Object.keys(newTableDescription));
        
    } catch (error) {
        console.error('添加字段失败:', error);
        throw error;
    }
}

if (require.main === module) {
    (async () => {
        try {
            await addUserProfileFields();
            console.log('用户信息字段添加成功完成');
            process.exit(0);
        } catch (error) {
            console.error('用户信息字段添加失败:', error);
            process.exit(1);
        }
    })();
}

module.exports = { addUserProfileFields }; 